package com.example.linearlayoutdemo.network.auth.viewmodel;

import android.app.Application;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;

import com.example.linearlayoutdemo.network.auth.model.RegisterResponse;
import com.example.linearlayoutdemo.network.auth.model.User;
import com.example.linearlayoutdemo.network.auth.repository.AuthRepository;
import com.example.linearlayoutdemo.network.auth.auth.ApiService;

/**
 * 注册ViewModel，处理注册相关业务逻辑
 */
public class RegisterViewModel extends AndroidViewModel {
    private final AuthRepository authRepository;

    // 用于观察的LiveData
    public final MutableLiveData<Boolean> isLoading = new MutableLiveData<>();
    public final MutableLiveData<String> errorMessage = new MutableLiveData<>();
    public final MutableLiveData<Boolean> registerSuccess = new MutableLiveData<>();

    public RegisterViewModel(@NonNull Application application) {
        super(application);
        authRepository = AuthRepository.getInstance(application);
    }

    /**
     * 执行注册操作
     */
    public void register(String username, String password, String email) {
        // 输入验证
        if (username.isEmpty() || password.isEmpty() || email.isEmpty()) {
            errorMessage.setValue("所有字段都不能为空");
            return;
        }

        if (!isValidEmail(email)) {
            errorMessage.setValue("请输入有效的邮箱地址");
            return;
        }

        if (password.length() < 6) {
            errorMessage.setValue("密码长度不能少于6位");
            return;
        }

        isLoading.setValue(true);
        User user = new User(username, password, email);

        authRepository.register(user, new ApiService.ApiCallback<RegisterResponse>() {
            @Override
            public void onStart() {
                isLoading.setValue(true);
            }

            @Override
            public void onSuccess(RegisterResponse response) {
                if (response.isSuccess()) {
                    registerSuccess.setValue(true);
                } else {
                    errorMessage.setValue(response.getMessage() != null ? response.getMessage() : "注册失败");
                }
            }

            @Override
            public void onFailure(Exception e) {
                errorMessage.setValue(e.getMessage() != null ? e.getMessage() : "注册失败，请检查网络");
            }

            @Override
            public void onComplete() {
                isLoading.setValue(false);
            }
        });
    }

    /**
     * 简单验证邮箱格式
     */
    private boolean isValidEmail(String email) {
        return email.contains("@") && email.contains(".");
    }
}

